$().ready(function() {
	validateRule();
	$("#trainingForm_sn").html($("#commodityDescribe").val())
	$('#trainingForm_sn').summernote({
		height: '300px',
		lang: 'zh-CN',
		toolbar: [
			['style', ['bold', 'italic', 'underline', 'clear']],
			['font', ['strikethrough', 'superscript', 'subscript']],
			['fontsize', ['fontsize']],
			['fontname', ['fontname']],
			['color', ['color']],
			['para', ['ul', 'ol', 'paragraph']],
			['height', ['height']],
			['table', ['table']],
			['insert', ['link', 'picture']],
			['view', ['fullscreen', 'codeview', 'help']]
		],
		callbacks: {
			onImageUpload: function (files, editor, $editable) {
				sendFiles(files,'#trainingForm_sn');
			},
			onPaste: function (ne) {
				var bufferText = ((ne.originalEvent || ne).clipboardData || window.clipboardData).getData('Text/plain');
				ne.preventDefault ? ne.preventDefault() : (ne.returnValue = false);
				setTimeout(function () {
					document.execCommand("insertText", false, bufferText);
				}, 10);
			}
		}
	});
	//编辑器新增的ajax上传图片函数
	function sendFiles(files, editor, $editable) {
		var formData = new FormData();
		formData.append("file", files[0]);
		$.ajax({
			data : formData,
			type : "POST",
			url : "/common/sysFile/upload",    // 图片上传出来的url，返回的是图片上传后的路径，http格式
			cache : false,
			contentType : false,
			processData : false,
			dataType : "json",
			success: function(data) {//data是返回的hash,key之类的值，key是定义的文件名
				$(editor).summernote('insertImage',data.data);
			},
			error:function(data){
				//console.log("data",data)
				alert("上传失败");
			}
		});
	}
});


function save() {

	$.ajax({
		cache : true,
		type : "POST",
		url : "/jzweb/reserveStoreCommodity/save",
		data : $('#signupForm').serialize(),// 你的formid
		async : false,
		error : function(request) {
			parent.layer.alert("Connection error");
		},
		success : function(data) {
			if (data.code == 0) {
				parent.layer.msg("操作成功");
				parent.reLoad();
				var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
				parent.layer.close(index);
			} else {
				parent.layer.alert(data.msg)
			}

		}
	});

}


let valIdx = parseInt($("#type").val());
$("#types").find('option').each(function (k,v){

	if( k == ( valIdx - 1) ) {
		$("#types").val(valIdx)
	}
})

$("#types").change(function (ev){
	$("#type").val($(this).val())
})


$.validator.setDefaults({
	submitHandler : function() {
		update();
	}
});
function update() {
	let getUserIntegral = [], integralUser = [];

	//商品规格
	// $(".shopBox").find('.shopArg').each(function (index,val){
	// 	// getUserIntegral.push({'title': $(val).find('.shopModel').val(),'val': $(val).find('.shopSize').val()})
	// 	getUserIntegral.push($(val).find('.shopModel').val(),$(val).find('.shopSize').val())
	// })

	// $("#specificationName").val( JSON.stringify(getUserIntegral) )
	// $("#specificationName").val( getUserIntegral.join(',') )

	//商品参数
	$(".shopNew").find('.shopArg').each(function (index,val){
		integralUser.push({'title': $(val).find('.shopArguments').val(),'val': $(val).find('.shopVal').val()})
		// integralUser.push( $(val).find('.shopArguments').val(),$(val).find('.shopVal').val())
	})
	$("#commodityDescribe").val($('#trainingForm_sn').summernote('code'));

	$("#specification").val( JSON.stringify(integralUser) )

	$.ajax({
		cache : true,
		type : "POST",
		url : "/jzweb/reserveStoreCommodity/update",
		data : $('#signupForm').serialize(),// 你的formid
		async : false,
		error : function(request) {
			parent.layer.alert("Connection error");
		},
		success : function(data) {
			if (data.code == 0) {
				parent.layer.msg("操作成功");
				parent.reLoad();
				var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
				parent.layer.close(index);

			} else {
				parent.layer.alert(data.msg)
			}

		}
	});

}
function validateRule() {
	var icon = "<i class='fa fa-times-circle'></i> ";
	$("#signupForm").validate({
		rules : {
			name : {
				required : true
			}
		},
		messages : {
			name : {
				required : icon + "请输入名字"
			}
		}
	})
}

// 商品规格
// var localStorage = JSON.parse($('#specificationName').val());
//商品参数
var integralUser = JSON.parse($('#specification').val());
let str = '', srr ='';

// localStorage.forEach(function (k,v){
// 	if( v == 0 ){
// 		srr = `<p class="changeArg">添加规格</p>`;
// 	}else{
// 		srr = `<p class="changeArgDele">删除</p>`;
// 	}
// 	str += `
// 		<div class="shopArg">
// 			<input type="text" class="shopArguments" value="${ k.name }">
// 			<input type="text" class="shopVal" value="${ k.quantity }">
// 			<div class="clickInfinite">
// 				${srr}
// 			</div>
// 		</div>
// 	`;
// 	$(".shopNew").html(str);
// })

//商品参数
integralUser.forEach(function (k,v){
	if( v == 0 ){
		srr = `<p class="changeArg">添加规格</p>`;
	}else{
		srr = `<p class="changeArgDele">删除</p>`;
	}
	str += `
		<div class="shopArg">
			<input type="text" class="shopArguments" value="${ k.title }">
			<input type="text" class="shopVal" value="${ k.val }">
			<div class="clickInfinite">
				${srr}
			</div>
		</div>
	`;
	$(".shopNew").html(str);
})

$(".changeArg").click(function (){
	let str = `
		<div class="shopArg">
			<input type="text" class="shopArguments">
			<input type="text" class="shopVal">
			<div class="clickInfinite">
				<p class="changeArgDele">删除</p>
			</div>
		</div>
	`;
	$(".shopNew").append(str);
})

$(document).on('click','.changeArgDele',function (){
	$(".changeArgDele").each(function (index){
		$(this).attr('data-index',index);
	})
	$(".shopNew").find('.shopArg').eq(parseInt( $(this).attr('data-index') )+ 1).remove();
})


sizeInput()
function sizeInput(){
	$(document).on('input','.shopSize',function (val){
		$(".shopSize").each(function (index,val){
			$(val).attr('index',index)
			if( $(val).val() ){
				max[index] = parseInt($(val).val());
			}else{
				max[index] = 0;
			}
		})
		$("#inventoryQuantity").val( max.reduce((n,m) => n + m) )
	})
}

//图片上传
var arrImg = [];
layui.use('upload', function () {
	var upload = layui.upload;
	upload.render({
		elem: '#btnAdd',
		url: '/common/sysFile/upload',
		accept: 'images', //只允许上传图片
		acceptMime: 'image/*', //只筛选图片
		multiple:true,
		number:5,
		size:10240,
		done: function (r) {
			var str =  $("#commodityImg").val(),
				srr = str.split(',');

			srr.filter(function (k,v){
				console.log(k);
			})

			arrImg.push(r.data);
			arrImg = [...arrImg,...srr];

			srr = arrImg.join();
			$("#commodityImg").val(srr);

			invoking();
			arrImg = [];

		},
		error: function (r) {
			layer.msg(r.msg);
		}
	});
});


var listImg = [];
layui.use('upload', function () {
	var upload = layui.upload;
	upload.render({
		elem: '#btnAdd1',
		url: '/common/sysFile/upload',
		accept: 'images', //只允许上传图片
		acceptMime: 'image/*', //只筛选图片
		multiple:true,
		number:5,
		size:10240,
		done: function (r) {
			var str = $("#commodityParticularsImg").val(),
				srr = str.split(',');
			listImg.push(r.data);
			listImg = [...srr,...listImg]
			srr = listImg.join();
			$("#commodityParticularsImg").val(srr);

			invoking();
			listImg = [];

		},
		error: function (r) {
			layer.msg(r.msg);
		}
	});
})


function invoking(){
	var brand = $("#commodityImg").val().split(','), str = '',srr = '', moreImg = $("#commodityParticularsImg").val().split(',');

	brand = brand.filter(item => {
		return item.length > 0
	});
	brand.map(function (item, index) {
		str += `
			<div class="closeBtn"><img class="upImg" src="${item}" style="width: 150px; height:150px;"/><span class="iconclose"><img src="../../../../img/close.png"></span></div>
		`
		srr += item+',';
	})

	$("#brandImgs1").html(str);
	$("#brandImgs1").find(".iconclose").click(function (){
		let deleImg = $(this).parent('.closeBtn').find('img').attr('src')
		$(this).parent('.closeBtn').remove();
		brand.forEach(function (v,k){
			if ( deleImg == v ){
				brand.splice(k,1)
				$("#commodityImg").val(brand.join());
			}
		})
	})

	str = '';
	moreImg = moreImg.filter(item => {
		return item.length > 0
	});
	moreImg.map(function (item, index) {
		str += `<div class="closeBtn"><img class="upImg" src="${item}" style="width: 150px; height:150px;"/><span class="iconclose"><img src="../../../../img/close.png"></span></div>`
		srr += item+',';
	})

	$("#moreImg").html(str);
	$("#moreImg").find(".iconclose").click(function (){
		let deleImg = $(this).parent('.closeBtn').find('img').attr('src')
		$(this).parent('.closeBtn').remove();
		moreImg.forEach(function (v,k){
			if ( deleImg == v ){
				moreImg.splice(k,1)
				$("#commodityParticularsImg").val(moreImg.join());
			}
		})
	})

}

invoking();